<?php
namespace app\common\model;

use app\common\service\LangMap;
use think\facade\Db;
use think\model\concern\SoftDelete;

class UserPowerCardModel extends BaseModel
{
    use SoftDelete;

    protected $table = 'users_power_card';

    /**
     * @var MerchantModel|null
     * */
    public static $use_card_merchant_model = null;

    public static $fields_status = [
        ['name' => '未使用'],
        ['name' => '已使用'],
        ['name' => '已过期'],
        ['name' => '退卡'],
    ];

    public function getLocationAddrAttr($value){
        $province = $this['province'];
        $city = $this['city'];
        $area = $this['area'];
        $locationAddr = "";
        if(!empty($province)){
            $locationAddr .=$province.'/';
            if(!empty($city)){
                $locationAddr .=$city.'/';
            }
            if(!empty($area)){
                $locationAddr .=$area;
            }
        }
        return $locationAddr;
    }

    public function getLocationIntroAttr()
    {
        $location_addr = $this['location_addr'];
        if(empty($location_addr)){
            return '通用';
        }else{
            return $location_addr;
        }
    }

    public static function getCount($user_id = 0, $type = "")
    {
        if (empty($user_id)) {
            return 0;
        }

        $where = [];
        $where[] = ['uid', '=', $user_id];
        if ($type == 'used') {
            $where[] = ['status', '>', 0];
        } elseif ($type == 'reduce') {
            $where[] = ['status', '=', 0];
        }
        return self::where($where)->count();
    }

    //获取卡能否使用
    public function getCanUseAttr()
    {
        $can_use = 0; // 0-不能用 1-可用
        $status = $this['status'];
        $start_date = $this['start_date'];
        $end_date = $this['end_date'];
        $current_date = date('Y-m-d');
        if(empty($status)){
            if(!empty($end_date)){

                if(empty($start_date) &&  $current_date<=$end_date ){
                    $can_use=1;
                }elseif(!empty($start_date) && $current_date > $start_date &&  $current_date<=$end_date){
                    $can_use=1;
                }
            }else{
                if(empty($start_date)){ //永久有效
                    $can_use=1;
                }elseif($start_date<=$current_date){
                    $can_use=1;
                }
            }
        }

        $card_province = $this['province'];
        $card_city = $this['city'];
        //验证城市是否匹配
        if($can_use==1 && !empty($card_city) && !empty(self::$use_card_merchant_model)){ //验证是否可在商家使用

            $mch_province = self::$use_card_merchant_model['province'];
            $mch_city = self::$use_card_merchant_model['city'];
            if(!($mch_city == $card_city && $mch_province == $card_province)){
                $can_use = 0;
            }

        }

        return $can_use;
    }


    public function getUseIntroAttr()
    {
        $start_date = $this['start_date'];
        $end_date = $this['end_date'];
        if($start_date && $end_date){
            return "有效时间:$start_date~$end_date";
        }elseif($start_date){
            return "生效时间:$start_date";
        }elseif($end_date){
            return "结束时间:$end_date";
        }
    }




    /**
     * 获取数据
     * @param array $input_data 请求内容
     * @param int|null $limit 页面条数
     * @throws
     * @return \think\Paginator
     * */
    public static function getPageData(array $input_data=[])
    {
        $order_id = $input_data['order_id']??'';
        $mode = $input_data['mode']??'';
        $limit = $input_data['limit']??null;
        $where = [];

        if(app()->http->getName() != 'admin'){
            if($mode=='used'){ //不可用
                $where[] = ['status','>',0];
            }elseif($mode=='reduce'){//甚于数量
                $where[] = ['status','=',0];
            }else{//可用
                $where[] = ['status','=',0];
            }
        }


        if(!empty($order_id)){
            $where[] = ['oid','=',$order_id];
        }

        isset($input_data['uid']) && $where[]=['uid','=',$input_data['uid']];

        $search_month = $input_data['search_month']??'';
        if($search_month){
            $search_start_time = strtotime($search_month);
            $where[] = ['order_use_time','>=', $search_month];
            $where[] = ['order_use_time','<=',date('Y-m-d',strtotime('+1 month',$search_start_time))];
        }
//        dump($where);exit;
        $model = self::with(['linkUseMch','linkMch','linkOrder','linkOrderUse'])->where($where)->order('id desc')->paginate($limit);
        return $model;
    }


    //获得卡
    public static function orderCard(OrderModel $order_model,$card_reduce_money=0)
    {
        //卡使用信息
        $use_card_info = [];
        $integral = 0;
        $province = $city = $area = "";
        if($order_model['type']==3 && !empty($order_model['var_id'])){ //退卡反一张新卡
            $num = $all_num = 1;

        }elseif($order_model['type']==3){ //直接下单增加用户使用卡
            //查询订单使用设备信息
            $device_info = null;
            if(!empty($order_model['cond_id'])){
                $device_info = DeviceModel::find($order_model['cond_id']);
            }

            $num = $all_num = 1;
            $use_card_info =[
                'status' => 1,
                'mch_id'=>$order_model['mch_id'],
                'use_order_id'=>$order_model['id'],
                'use_mch_id'=>$order_model['mch_id'],
                'device_id'=>$order_model['cond_id'],
                'use_device_no'=>empty($device_info)?null:$device_info['no'],
                'order_use_time'=>date('Y-m-d H:i:s'),
            ];
        }else{
            $user_model = UserModel::find($order_model['uid']);
            $q_integral = $user_model['integral'];

            $var_id = $order_model['var_id'];
            $card_model = CardSoldModel::find($var_id);
            $num = $card_model['num']??0;
            $integral = $card_model['integral']??0;

            //奖励张数
            $award_num = (int)($card_model['award_num']??0);
            //次月 间隔多久发放一次
            $award_day = $card_model['award_day']??0;
            //有效时间
            $award_expire = $card_model['award_expire']??0;
            //有效时间
            $province = $card_model['province']??'';
            $city = $card_model['city']??'';
            $area = $card_model['area']??'';
            //获得能量卡
            $all_num = $num;
            if($award_num){
                $all_num = $num + $award_num;
            }
        }




        $commission_money = $all_num > 0 ? number2dot($card_reduce_money / $all_num) : 0 ;
        $card_data = [];
        for($i=0;$i<$all_num;$i++){
            $card_info = array_merge([
                'no'=>self::make_coupon_card(),
                'mch_id'=>$order_model['mch_id'],
                'oid'=>$order_model['id'],
                'uid'=>$order_model['uid'],
                'commission_money' => $commission_money,
                'date'=>date('Y-m-d'),
                'start_date'=>null,
                'end_date'=>null,
                'province'=>$province,
                'city'=>$city,
                'area'=>$area,
                'status'=>0,
                'is_gift'=> $i >= $num ? 1 : 0,
                'create_time'=>time(),
            ],$use_card_info);
            if( $i >= $num){ //奖励的数据
                if(!empty($award_day)){
                    $day = $award_day*($i-$num);
                    $strtotime = strtotime(date('Y-m'));
                    $card_info['start_date'] = date('Y-m-d',strtotime('+1 month +'.$day.' day',$strtotime));
                    if(!empty($award_expire)){
                        $card_info['end_date'] = date('Y-m-d',strtotime('+'.($award_expire-1).' day',strtotime($card_info['start_date'])));
                    }
                }elseif(!empty($award_expire)){
                    $card_info['end_date'] = date('Y-m-d',strtotime('+'.($award_expire-1).' day'));
                }

            }
            $card_data[] = $card_info;
        }
        if($order_model['type']==3 && empty($order_model['var_id']) && count($card_data)==1) {
            $insert_id = UserPowerCardModel::insertGetId($card_data[0]);
            $order_model->setAttr('var_id',$insert_id);
            $order_model->save();
        }else{
            UserPowerCardModel::insertAll($card_data);
        }

        //
        if($integral>0){
            //奖励积分数量
            $order_model->setAttr('award_integral',$integral);
            $order_model->save();

            UserModel::where(['id'=>$user_model['id']])->update([
                'integral' => Db::raw('integral+'.$integral),
                'history_integral' => Db::raw('history_integral+'.$integral),
            ]);
            UserLogsModel::recordData(1,$user_model['id'],$integral,"购卡获得能量值,订单单号:".$order_model['no'],[
                'q_money'=>$q_integral,'h_money'=>$q_integral+$integral,'m_type'=>0,
                'order_id'=>$order_model['id']
            ]);
        }

    }

    public function apiFullInfo()
    {
        return array_merge($this->apiNormalInfo(),[
            'back_state'=>(int)$this['back_state'],
            'back_intro'=>(string)$this['back_intro'],
            'back_time'=>(string)$this['back_time'],
        ]);
    }

    public function apiNormalInfo()
    {
        $linkMch = $this->getRelation('linkMch');
        $linkUseMch = $this->getRelation('linkUseMch');
        $linkOrder = $this->getRelation('linkOrder');
        $linkOrderUse = $this->getRelation('linkOrderUse');

        $status = $this['status'];
        return [
            'id' => $this['id'],
            'date' => (string)$this['date'],
            'no'=> (string)$this['no'],
            'use_date' => (string)$this['use_date'],
            'use_month' => empty($this['order_use_time'])?'':substr($this['order_use_time'],5,5),
            'use_hour' => empty($this['order_use_time'])?'':substr($this['order_use_time'],11,5),
            'create_time' => (string)$this['create_time'],
            'num' => 1,
            'status' => $status,
            'status_intro' => self::getPropInfo('fields_status',$status,'name'),
            'use_intro' =>(string)$this['use_intro'],
            'can_use' =>(int)$this['can_use'],
            'commission_money'=>$this['commission_money'],
            "commission_send_date"=>$this['commission_send_date'],
            "device_id"=>$this['device_id'],
            "use_device_no"=>$this['use_device_no'],
            "order_use_time"=>$this['order_use_time'],
            "is_gift"=>$this['is_gift'],

            'mch_id' => empty($linkMch)?0:$linkMch['id'],
            'mch_name' => empty($linkMch)?'':$linkMch['name'],
            'mch_addr' => empty($linkMch)?'':$linkMch['addr'],

            'use_mch_id' => empty($linkUseMch)?0:$linkUseMch['id'],
            'use_mch_name' => empty($linkUseMch)?'':$linkUseMch['name'],
            'use_mch_addr' => empty($linkUseMch)?'':$linkUseMch['addr'],

            'order_id' => empty($linkOrderUse)?0:$linkOrderUse['id'],
            'order_no' => empty($linkOrderUse)?'':$linkOrderUse['no'],
            'order_service_time_intro' => empty($linkOrderUse)?'':$linkOrderUse['service_time_intro'],

            'location_addr' => (string)$this['location_addr'],
            'location_intro'    => (string)$this['location_intro'],
        ];
    }

    public function linkMch()
    {
        return $this->belongsTo(MerchantModel::class,'mch_id');
    }
    public function linkUseMch()
    {
        return $this->belongsTo(MerchantModel::class,'use_mch_id');
    }
    public function linkOrder()
    {
        return $this->belongsTo(OrderModel::class,'oid');
    }
    public function linkOrderUse()
    {
        return $this->belongsTo(OrderModel::class,'use_order_id');
    }
}